from os.path import isdir
from openpyxl import Workbook
from openpyxl import load_workbook
import csv
import os
import sys
import shutil
from datetime import datetime


def circleBuildExcelBaseConfig(parentPath, infoPath, outPath):
    if not os.path.exists(outPath):
        os.mkdir(outPath)
    config_files = os.listdir(infoPath)
    for filename in config_files:
        infoJson = {}
        if os.path.isdir(os.path.join(infoPath, filename)):
            print("d")
            circleBuildExcelBaseConfig(
                parentPath,
                os.path.join(infoPath, filename),
                os.path.join(outPath, filename),
            )
        else:
            print("f")
            shutil.copy(
                os.path.join(parentPath, "test.xlsx"),
                os.path.join(outPath, "{}.xlsx".format(filename)),
            )
            with open(os.path.join(infoPath, filename)) as f:
                render = csv.reader(f)  # reader(迭代器对象)--> 迭代器对象
                # 取表头
                header_row = next(render)
                for row in render:
                    infoJson[row[0]] = row
            excel_file = os.path.join(outPath, "{}.xlsx".format(filename))
            time_now = datetime.now()
            current_time = time_now.strftime("%H:%M:%S")
            wb = load_workbook(filename=excel_file)
            sheet = wb["当前版本"]
            sheet2 = wb["升级记录"]
            sheet2["A2"] = "uip"
            sheet2["B2"] = current_time
            sheet2["C2"] = "张新华"
            sheet2["D2"] = "统一升级"
            sheet2["E2"] = "凌志阳"
            sheet2["F2"] = "数据清洗"
            sheet2["A3"] = ""
            for index in range(3, 28, 1):
                module_name = sheet["C{}".format(index)].value
                if module_name in infoJson:
                    moduleInfo = infoJson[module_name]
                    sheet["D{}".format(index)] = moduleInfo[1]
                    sheet["E{}".format(index)] = moduleInfo[2]
            wb.save(filename=excel_file)


if __name__ == "__main__":
    parentPath = sys.path[0]
    infoPath = os.path.join(parentPath, "infos")
    outPath = os.path.join(parentPath, "output")
    if len(sys.argv) > 1:
        infoPath = sys.argv[1]
    if len(sys.argv) > 2:
        outPath = sys.argv[2]
    print("infoPath:" + infoPath)
    print("outPath:" + outPath)
    circleBuildExcelBaseConfig(parentPath, infoPath, outPath)
